package evolution.cli;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import evolution.Directory;
import evolution.File;
import evolution.ResourceException;


public class FileSystemFile implements File
{
	private final java.io.File delegate;
	private Directory parent;

	public FileSystemFile(java.io.File delegate)
	{
		this.delegate = delegate;
	}

	public String getName()
	{
		return delegate.getName();
	}

	public Reader getReader() throws ResourceException
	{
		try
		{
			return new FileReader(delegate);
		}
		catch (FileNotFoundException e)
		{
			throw new ResourceException("Failed to read file: " + delegate, e);
		}
	}

	public Writer getWriter() throws ResourceException
	{
		try
		{
			return new FileWriter(delegate);
		}
		catch (IOException e)
		{
			throw new ResourceException("Failed to write to file: " + delegate, e);
		}
	}

	public void setParent(Directory parent)
	{
		this.parent = parent;
	}

	@Override
	public String toString()
	{
		return delegate.toString();
	}

	public String getPath()
	{
		if (parent != null)
		{
			String parentPath = parent.getPath();
			if (parentPath.equals("/"))
			{
				return "/" + getName();
			}
			else
			{
				return parentPath + "/" + getName();
			}
		}
		else
		{
			return getName();
		}
	}

	public long getLastModifiedTime()
	{
		return delegate.lastModified();
	}

}
